package com.jboost.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author yanfei
 */
@Slf4j
public class UploadImageUtils {

    public static String uploadImage(MultipartFile file) throws FileNotFoundException {
        if (file.isEmpty()) {
            log.debug("文件不存在");
        }
        String path = ResourceUtils.getURL("").getPath();
        File filePath = new File(path, "upload/");
        String fileName = file.getOriginalFilename();
        // 文件名
        assert fileName != null;
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 后缀名
        fileName = UUID.randomUUID() + suffixName;
        // 新文件名
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        File dest = new File(filePath + "/" + df.format(new Date()) + "/" + fileName);
        /*不存在路径就创建*/
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        /*上传图片*/
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path + "/upload/" + df.format(new Date()) + "/" + fileName;
    }

}
